<?php

namespace Modules\Code\Exports;

use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithTitle;

use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

// use PHPExcel_Cell_DataType;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

use Modules\Order\Entities\Order;

class CodeExport implements WithColumnFormatting, FromCollection, WithTitle, WithHeadings, WithMapping, ShouldAutoSize
{
    use Exportable;

    private $list;

    public function __construct($list)
    {
        $this->list = $list;
    }

    public function columnFormats(): array
    {
        return [];
        // return [
        //     'O' => DataType::TYPE_STRING
        // ];
    }

    /**
     * @return Builder
     */
    public function collection()
    {
        return $this->list;
        // return BookInfo::where('booking_session_id', $this->session->id)->displayed();
    }

    /**
     * @return string
     */
    public function title(): string
    {
        return '激活码导出';
    }

    public function map($item): array
    {
        $map = [
            'score' => '积分',
            'redpack' => '红包',
            'card' => '卡券',
            'coupon' => '优惠券',
            'chip' => '碎片'
        ];

        $content = '-';

        if ($item->code_type === 'score') {
            $content = $item->score . '积分';
        }
        elseif ($item->code_type === 'redpack') {
            $content = $item->redpack / 100 . '红包';
        }
        elseif ($item->code_type === 'coupon') {
            if ($item->coupon) {
                $content = $item->coupon->title;
            }
        }

        return [
            $item->title,
            $item->batch_number,
            $item->code,
            @$map[$item->code_type] ?: '-',
            $content,
            $item->stock,
            $item->sales ?: 0,
            (String)$item->created_at,
            env('APP_URL') . '/miniapp/qrcode?path=' . urlencode('/pages/code/index?code=') . $item->code
        ];
    }

    public function headings(): array
    {
        return [
            '标题',
            '批次',
            '兑换码',
            '兑换类型',
            '兑换内容',
            '剩余库存',
            '已兑换',
            '创建日期',
            '小程序码'
        ];
    }
}
